<?php
namespace app\controller;
class Cty
{
    public function com_create_guid()
    {

        return sprintf('%04x%04x-%04x-%04x-%04x-%04x%04x%04x',

            mt_rand(0, 0xffff), mt_rand(0, 0xffff),

            mt_rand(0, 0xffff),

            mt_rand(0, 0x0fff) | 0x4000,

            mt_rand(0, 0x3fff) | 0x8000,

            mt_rand(0, 0xffff), mt_rand(0, 0xffff), mt_rand(0, 0xffff)

        );

    }

//   lg 相当于c#main中todo
    public function ctyun($SecurityKey, $accessKey, $url, $query, $header, $body, $flag, $contextType, $fileMap)
    {

        date_default_timezone_set('Asia/Shanghai');
        $uuid = $this->com_create_guid();

        $time = date('Ymd', time()) . 'T' . date('His') . 'Z';

        $timeDate = substr($time, 0, 8);

        //传递的参数
        $postFields = '';
        //填充header参数中的contentType
        $headers = array(); //准备对他塞数据
        if (str_contains($contextType, 'application/json')) {
            $headers[0] = 'Content-Type:application/json';

            $postFields = json_encode($body);

        }

        //为什么要排序
        $query = $this->encodeQueryStr($query);
        if ($query != null && $query != "") {
            $url = $url . "?" . $query;

        }else{
        }

        $body = bin2hex(hash("sha256", $postFields, true));

        //$strsignature = "ctyun-eop-request-id:" . $uuid . "\n" . "eop-date:" . $time . "\n" . "\n" . $query . "\n" . $body;
        $strsignature = "ctyun-eop-request-id:".$uuid."\n"."eop-date:".$time."\n\n".$query."\n".$body;
        //$strsignature = "ctyun-eop-request-id:" . $uuid  . "eop-date:" . $time  . $query  . $body;

        $Ktime = $this->en($time, $SecurityKey);

        $kAk = $this->en($accessKey, $Ktime);

        $kdate = $this->en($timeDate, $kAk);

        $signature = base64_encode(($this->en($strsignature, $kdate)));

        //print_r($signature);
        //lg
        $header1 = array(
            'ctyun-eop-request-id:' . $uuid,
            'appkey:'.'c0b71c83e6ae902d68d9334e6410fb1c',
            'Eop-Authorization:' . $accessKey . ' Headers=ctyun-eop-request-id;' . 'eop-date Signature=' . $signature,
            'eop-date:' . $time,
        );
        $header = array_merge_recursive($header1, $header, $headers);
        //dump($header);
        //
//        var_dump("xxxxx");
//        var_dump($postFields);
//        var_dump("yyyyy");
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); // 跳过证书检查
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false); // 从证书中检查SSL加密算法是否存在
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_POST, true);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $postFields);
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_HTTPHEADER, $header);//header请求。如不需要可以去掉
        //curl_setopt($ch, CURLOPT_HEADER, true); // 包含头部信息

        //dump($header);

        $response = curl_exec($ch);

        if ($response === false) {
            $error = curl_error($ch);
            curl_close($ch);
            // 抛出一个异常或返回错误信息
            //throw new Exception("CURL Error: " . $error);
            var_dump($error);

        }else{

            //var_dump($response);
        }

        $response = json_decode($response, true);
        return $response;
    }

    public function en($str, $pass)
    {
        $ret = (hash_hmac("sha256", ($str), ($pass), true));
        return $ret;
    }

    public function encodeQueryStr($str)
    {
        $afterQuery = "";
        if (!empty($str)) {
            $param = explode("&", $str);
            Var_dump($param);
            sort($param);
            Var_dump($param);
            foreach ($param as $arr) {
                if (strlen($afterQuery) < 1) {
                    $s = explode("=", $arr);
                    Var_dump($s);
                    if (count($s) >= 2) {
                        echo count($s);
                        $encodeStr = "";
                        $encodeStr = urlencode($s[1]);
                        Var_dump($s);
                        $arr = $s[0] . "=" . $encodeStr;
                        $afterQuery = $afterQuery . $arr;
                    } else {
                        $encodeStr = "";
                        $arr = $s[0] . "=" . $encodeStr;
                        $afterQuery = $afterQuery . $arr;
                    }
                } else {
                    $s = explode("=", $arr);
                    if (count($s) >= 2) {
                        $encodeStr = urlencode($s[1]);
                        $arr = $s[0] . "=" . $encodeStr;
                        $afterQuery = $afterQuery . "&" . $arr;
                    } else {
                        $encodeStr = "";
                        $arr = $s[0] . "=" . $encodeStr;
                        $afterQuery = $afterQuery . "&" . $arr;
                    }
                }
            }
        }
        return $afterQuery;
    }

    public static function get_byteList($fileMap,$uuid,$body){
        $byteList = '';
        $contentType = 'multipart/form-data; boundary='.$uuid;
        $boundary = $uuid;
        $boundary = '--'.$boundary;
        $order3 = "\r\n";
        foreach ($fileMap as $key => $value) {
            if (filesize($value) > 1048576) {
                echo "文件过大";
            }
            $body1 = $boundary . "\r\n" .
                "Content-Disposition: form-data; name=\"" . $key . "\"; filename=\"" . basename($value) . "\r\n" .
                "Content-Type: application/octet-stream" . "\r\n" . "\r\n";
            $order1 = ($body1);
            $order2 = (self::readbytes($value));
            $byteList = $byteList . $order1 . $order2 . $order3;
        }

        foreach ($body as $key => $value) {
            $body1 = '--' . $boundary . "\r\n" . "Content-Disposition: form-data; name=" . $key . "\r\n" . "\r\n" . $value . "\r\n";
            $byteList = $byteList. $body1. $order3;
        }
        $byteList = $byteList . $boundary . '--' . $order3;

        return $byteList;
    }

    public static function tostr($bytes) {
        $str = '';
        foreach ($bytes as $ch) {
            $str .= chr($ch);
        }
        return $str;
    }

    public static function readbytes($filename) {

        $handle = fopen($filename,"rb");
        $contents = fread($handle,filesize($filename));
        fclose($handle);
        return $contents;
    }
}
